<template>
  <div class="material-order-detail">
    <el-card v-loading="loading">
      <div slot="header" class="header">
        <h2>订单详情</h2>
        <div class="header-actions">
          <el-button 
            v-if="order && order.status === 'pending'" 
            type="success" 
            @click="goToPayment"
          >
            去支付
          </el-button>
          
          <el-button 
            v-if="order && (order.status === 'paid' || order.status === 'completed')" 
            type="primary" 
            @click="downloadMaterial"
          >
            下载材料
          </el-button>
          
          <el-button 
            v-if="order && order.status === 'pending'" 
            type="danger" 
            @click="cancelOrder"
          >
            取消订单
          </el-button>
          
          <el-button @click="backToList">返回列表</el-button>
        </div>
      </div>
      
      <!-- 订单不存在 -->
      <div v-if="!loading && !order" class="order-not-found">
        <el-result icon="error" title="订单不存在" subTitle="无法找到该订单信息，请检查订单号是否正确">
          <template slot="extra">
            <el-button type="primary" @click="backToList">返回订单列表</el-button>
          </template>
        </el-result>
      </div>
      
      <!-- 订单详情 -->
      <div v-else-if="order" class="order-info">
        <!-- 订单状态 -->
        <div class="order-status">
          <el-steps :active="getStatusStep(order.status)" finish-status="success" simple>
            <el-step title="创建订单" :description="formatDate(order.createdAt)"></el-step>
            <el-step title="支付" :description="order.paidAt ? formatDate(order.paidAt) : '未支付'"></el-step>
            <el-step title="完成" :description="order.completedAt ? formatDate(order.completedAt) : '未完成'"></el-step>
          </el-steps>
        </div>
        
        <!-- 订单基本信息 -->
        <el-descriptions title="订单信息" :column="2" border>
          <el-descriptions-item label="订单号">{{ order.orderNumber }}</el-descriptions-item>
          <el-descriptions-item label="订单状态">
            <el-tag :type="getStatusType(order.status)">{{ getStatusText(order.status) }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatDate(order.createdAt) }}</el-descriptions-item>
          <el-descriptions-item label="支付时间">{{ order.paidAt ? formatDate(order.paidAt) : '未支付' }}</el-descriptions-item>
          <el-descriptions-item label="支付金额">
            <span class="price">¥{{ order.totalAmount }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="支付方式">
            {{ getPaymentMethodText(order.paymentMethod) }}
          </el-descriptions-item>
        </el-descriptions>
        
        <!-- 材料信息 -->
        <div v-if="order.material" class="material-info">
          <h3>材料信息</h3>
          <el-card shadow="never" class="material-card">
            <div class="material-header">
              <div class="material-title">{{ order.material.title }}</div>
              <div class="material-price">¥{{ order.material.price }}</div>
            </div>
            
            <div class="material-description">
              {{ order.material.description || '暂无描述' }}
            </div>
            
            <div class="material-meta">
              <span>
                <i class="el-icon-document"></i>
                {{ order.material.fileType || '未知格式' }}
              </span>
              <span>
                <i class="el-icon-download"></i>
                {{ order.material.downloadCount || 0 }}次下载
              </span>
              <span>
                <i class="el-icon-view"></i>
                {{ order.material.viewCount || 0 }}次浏览
              </span>
            </div>
          </el-card>
        </div>
        
        <!-- 下载记录 -->
        <div v-if="order.downloads && order.downloads.length > 0" class="download-history">
          <h3>下载记录</h3>
          <el-table :data="order.downloads" style="width: 100%">
            <el-table-column prop="downloadTime" label="下载时间" width="180">
              <template slot-scope="scope">
                {{ formatDate(scope.row.downloadTime) }}
              </template>
            </el-table-column>
            <el-table-column prop="ip" label="IP地址" width="180" />
            <el-table-column prop="userAgent" label="设备信息" />
          </el-table>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import { getMaterialOrder, cancelMaterialOrder, generateDownloadToken } from '@/api/material';

export default {
  name: 'MaterialOrderDetail',
  
  data() {
    return {
      orderNumber: this.$route.params.orderNumber,
      loading: true,
      order: null
    };
  },
  
  created() {
    this.fetchOrderDetails();
  },
  
  methods: {
    // 获取订单详情
    async fetchOrderDetails() {
      try {
        this.loading = true;
        const response = await getMaterialOrder(this.orderNumber);
        this.order = response.data;
      } catch (error) {
        this.$message.error('获取订单详情失败: ' + (error.message || '未知错误'));
      } finally {
        this.loading = false;
      }
    },
    
    // 获取状态步骤
    getStatusStep(status) {
      switch (status) {
        case 'pending':
          return 1;
        case 'paid':
          return 2;
        case 'completed':
          return 3;
        case 'cancelled':
          return 0; // 取消订单显示为第一步
        default:
          return 0;
      }
    },
    
    // 获取状态类型
    getStatusType(status) {
      switch (status) {
        case 'pending':
          return 'warning';
        case 'paid':
        case 'completed':
          return 'success';
        case 'cancelled':
          return 'info';
        default:
          return 'info';
      }
    },
    
    // 获取状态文本
    getStatusText(status) {
      switch (status) {
        case 'pending':
          return '待支付';
        case 'paid':
          return '已支付';
        case 'completed':
          return '已完成';
        case 'cancelled':
          return '已取消';
        default:
          return '未知状态';
      }
    },
    
    // 获取支付方式文本
    getPaymentMethodText(method) {
      if (!method) return '未支付';
      
      switch (method) {
        case 'balance':
          return '余额支付';
        case 'alipay':
          return '支付宝';
        case 'wechat':
          return '微信支付';
        default:
          return method;
      }
    },
    
    // 格式化日期
    formatDate(dateString) {
      if (!dateString) return '';
      const date = new Date(dateString);
      return date.toLocaleString();
    },
    
    // 前往支付页面
    goToPayment() {
      this.$router.push(`/payment/material/${this.orderNumber}`);
    },
    
    // 下载材料
    async downloadMaterial() {
      try {
        this.$message.info('正在准备下载...');
        const response = await generateDownloadToken(this.orderNumber);
        
        if (response.data && response.data.downloadUrl) {
          window.open(response.data.downloadUrl, '_blank');
          this.$message.success('开始下载材料');
          
          // 刷新订单详情
          setTimeout(() => {
            this.fetchOrderDetails();
          }, 1000);
        } else {
          this.$message.error('获取下载链接失败');
        }
      } catch (error) {
        this.$message.error('下载材料失败: ' + (error.message || '未知错误'));
      }
    },
    
    // 取消订单
    async cancelOrder() {
      try {
        await this.$confirm('确定要取消该订单吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        
        await cancelMaterialOrder(this.orderNumber);
        this.$message.success('订单已取消');
        
        // 刷新订单详情
        this.fetchOrderDetails();
      } catch (error) {
        if (error === 'cancel') {
          return;
        }
        this.$message.error('取消订单失败: ' + (error.message || '未知错误'));
      }
    },
    
    // 返回订单列表
    backToList() {
      this.$router.push('/materials/orders');
    }
  }
};
</script>

<style lang="scss" scoped>
.material-order-detail {
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    h2 {
      margin: 0;
    }
  }
  
  .order-status {
    margin: 20px 0 30px;
  }
  
  .material-info {
    margin-top: 30px;
    
    .material-card {
      margin-top: 15px;
      
      .material-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 15px;
        
        .material-title {
          font-size: 18px;
          font-weight: bold;
        }
        
        .material-price {
          font-size: 18px;
          color: #f56c6c;
          font-weight: bold;
        }
      }
      
      .material-description {
        color: #606266;
        margin-bottom: 15px;
      }
      
      .material-meta {
        display: flex;
        color: #909399;
        
        span {
          margin-right: 20px;
          
          i {
            margin-right: 5px;
          }
        }
      }
    }
  }
  
  .download-history {
    margin-top: 30px;
  }
  
  .price {
    font-size: 16px;
    font-weight: bold;
    color: #f56c6c;
  }
}
</style>